import requests, json, os
from abc import ABC
from . import *
# from . import abogus


class Api(ABC):
    __slots__ = ('logging', 'body', 'query',
                 'host', 'header', 'jwt', 'id',
                 'loginUrlPath', 'uploadDarenInfoUrlPath', 'downloadDarenInfoUrlPath', 'updateDarenInfoUrlPath')

    def __init__(self, *args, **kwargs):
        super(Api, self).__init__()
        self.host = kwargs.get('api', '')
        if not self.host:
            self.host = 'http://phonetool.mashangxuanpin.com' if setting.get('env', 'PRODUCTION') == 'DEBUG' else 'http://phonetool.mashangxuanpin.com'
            # self.host = 'http://192.168.0.101:9501' if setting.get('env', 'PRODUCTION') == 'DEBUG' else 'http://phonetool.mashangxuanpin.com'
        self.header = kwargs.get('header', {})
        if not self.header:
            self.header = {
                'Content-Type': 'application/json'
            }
        self.body = kwargs.get('body', {})
        self.query = kwargs.get('query', {})

        self.loginUrlPath = '/member/login'
        self.uploadDarenInfoUrlPath = '/jinritemai/kol/create'
        self.downloadDarenInfoUrlPath ='/jinritemai/kol/list'
        self.updateDarenInfoUrlPath = '/jinritemai/kol/#id#/edit'

    def updateDarenInfo(self):
        """
        编辑达人数据
        """
        logging.info(f'调用后台接口修改达人数据: {self.query} - {self.header}')
        path = self.updateDarenInfoUrlPath.replace("#id#", str(self.id))
        url = f'{self.host}{path}'
        resp = requests.put(url, headers=self.header, data=json.dumps(self.body))

        if not resp.ok:
            logging.error(f'接口not ok: {url} - {self.body} - {self.header}')
            return False
        resp = resp.json()
        logging.info(f'编辑达人数据接口的resp: {resp}')
        if resp.get('errno', 999) != '000':
            logging.error(f'编辑达人接口调用失败: {resp.get("errno")} - {resp.get("errmsg", "aaa")}')
            return False
        # ret = resp.get('result', {}).get('data', {}).get('id', 0)
        ret = {
            'id': resp.get('result', {}).get('data', {}).get('id', 0),
            'nickname': resp.get('result', {}).get('data', {}).get('nickname', '')
        }
        return ret

    def uploadDarenInfo(self):
        """
        创建数据
        """
        logging.info(f'调用后台接口上传达人数据: {self.query} - {self.header}')
        url = f'{self.host}{self.uploadDarenInfoUrlPath}'
        resp = requests.post(url, headers=self.header, data=json.dumps(self.body))

        if not resp.ok:
            logging.error(f'接口not ok: {url} - {self.body} - {self.header}')
            return False
        resp = resp.json()
        logging.info(f'上传达人数据接口的resp: {resp}')
        if resp.get('errno', 999) != '000':
            logging.error(f'上传达人接口调用失败: {resp.get("errno")} - {resp.get("errmsg", "aaa")}')
            if '已经存在请勿重复添加' in resp.get('msg', ''):
                return {'id': 0}
            return False
        res = resp.get('result', {}).get('data', {})
        ret = {
            'id': res.get('id', 0),
            'mobile': res.get('mobile', ''),
            'wechat': res.get('wechat', ''),
            'nickname': res.get('nickname', ''),
            'avatar': res.get('avatar', ''),
            'fans_num': res.get('fans_num', 0),
            'level': res.get('level', 0),
            'exists': res.get('exists', 0)
        }
        return ret
        # logging.info(f'往{self.uploadDarenInfoUrlPath}接口上传{self.body}')
        # return {'res': True}

    def downloadDarenInfo(self):
        """
        导出数据
        """
        logging.info(f'调用后台导出数据接口: {self.query} - {self.header}')
        url = f'{self.host}{self.downloadDarenInfoUrlPath}'
        resp = requests.post(url, headers=self.header, data=json.dumps(self.body))

        if not resp.ok:
            logging.error(f'接口not ok: {url} - {self.body} - {self.header}')
            return False
        resp = resp.json()
        logging.info(f'下载达人数据接口的resp: {resp}')
        if resp.get('errno', 999) != '000':
            logging.error(f'下载达人数据接口调用失败: {resp.get("errno")} - {resp.get("errmsg", "aaa")}')
            return False

        res = resp.get('result', {})
        if not res:
            logging.error(f'没有数据: {resp}')
            return False
        """
        # 测试用
        pages = 19
        perPage = 10
        total = pages * perPage
        data = []
        for x in range(total):
            data.append({'uid': x})
        res = {
            'data': data,
            'meta': {
                'total': total,
                'total_pages': pages,
                'current_page': 1,
                'count': total,
                'links': {}
            }
        }
        """
        ret = {
            'pages': res.get('meta', {}).get('total_pages'), 
            'data': res.get('data', [])
        }
        return ret

    def login(self):
        """
        登陆
        """
        logging.info(f'调用后台登陆接口')
        url = f'{self.host}{self.loginUrlPath}'
        resp = requests.post(url, headers=self.header, data=json.dumps(self.body))
        
        if not resp.ok:
            logging.error(f'接口not ok: {url} - {self.body} - {self.header}')
            return False
        resp = resp.json()
        logging.info(f'登陆的resp: {resp}')
        if resp.get('errno', 999) != '000':
            logging.error(f'登陆接口调用失败: {resp.get("errno")} - {resp.get("errmsg", "aaa")}')
            return False

        return resp.get('result', {})
    